package com.seer.auto.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.springframework.jdbc.core.PreparedStatementCreator;

public class DefaultPreparedStatementCreator implements PreparedStatementCreator {

    private Long id;
    private List<String> fields;
    private List<Object> values;
    private String table;

    public static PreparedStatementCreator getDefault(Long id, String table, List<String> fields, List<Object> values) {
        DefaultPreparedStatementCreator c = new DefaultPreparedStatementCreator();
        c.id = id;
        c.fields = fields;
        c.values = values;
        c.table = table;
        return c;
    }

    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        String sql = id == null ? insertSql() : updateSql();
        PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        int i = 1;
        for (Object o : values) {
            ps.setObject(i++, o);
        }
        if (null != id) {
            ps.setObject(i, id);
        }
        return ps;
    }

    private String insertSql() {
        String sql = "INSERT INTO %s(%s) VALUES(%s);";
        char[] cs = new char[fields.size() * 2 - 1];
        for (int i = 0; i < cs.length; i++) {
            if ((i & 1) == 1) {
                cs[i] = ',';
            } else {
                cs[i] = '?';
            }
        }
        return String.format(sql, table, String.join(", ", fields), new String(cs));
    }

    private String updateSql() {
        String sql = "UPDATE %s SET %s WHERE id = ?;";
        StringBuilder sb = new StringBuilder();
        for (String s : fields) {
            sb.append(s).append(" = ?, ");
        }
        sb.delete(sb.length() - 2, sb.length());
        return String.format(sql, table, sb.toString());
    }
}
